import Vue from 'vue'
import $http from '@/api/server/http'
import { cloneDeep } from 'lodash'

export const eventBus = new Vue()

const state = {
  queryStatus: 'done'
}

const mutations = {
  QUERY_STATUS: (state, data) => {
    state.queryStatus = data
  },
  SET_DICTIONARY: (state, payload) => {
    const clone = cloneDeep(state)
    if (!clone[payload.key.type]) {
      clone[payload.key.type] = {}
    }
    clone[payload.key.type].data = payload.value
    clone[payload.key.type].status = payload.status
    Vue.set(state, payload.key.type, clone[payload.key.type])
  }
}

const actions = {
  getDictionaryData({ state, commit }, type) {
    if ((state[type] && state[type].status === 200) || (state[type] && state[type].status === 'pending')) {
      return Promise.resolve()
    }
    commit('SET_DICTIONARY', {
      status: 'pending',
      key: type,
      value: []
    })
    const userInfo = Vue.prototype.$userInfo
    const config = {
      headers: {
        Authorization: 'Bearer ' + userInfo.token
      }
    }
    // const userInfo = Vue.prototype.$userInfo
    const getData = $http.get('dictionary', { params: { systemCode: type.systemCode, typeCode: type.type }, ...config })
    return getData
    // if (dictType === 1) {
    //   getData = $http.get('dictionary', { systemCode: dictType, typeCode: type, clientId: userInfo.clientId })
    // } else {
    //   getData = $http.get('dictionary', { systemCode: dictType, typeCode: type })
    // }
      .then(res => {
        if (res.data.code !== '0') {
          commit('SET_DICTIONARY', {
            status: res.status,
            key: type,
            value: []
          })
          throw Error('接口返回数据不对')
        }
        commit('SET_DICTIONARY', {
          status: res.status,
          key: type,
          value: res.data.data
        })
        return res.data.data
      })
      .catch((err) => {
        commit('SET_DICTIONARY', {
          status: err.response.status,
          key: type,
          value: []
        })
        throw err
      })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
